package com.tjs.netty.handler;

import com.alibaba.fastjson.JSONObject;
import com.tjs.netty.medium.Media;
import com.tjs.netty.param.Response;
import com.tjs.netty.param.ServerRequest;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

public class ServerHandler extends ChannelInboundHandlerAdapter {

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		System.out.println("server received = " + msg.toString());
		
		ServerRequest request = JSONObject.parseObject(msg.toString(), ServerRequest.class);

	/*	//TODO 以后做业务逻辑处理
		Response resp = new Response();
		resp.setId(request.getId());
		resp.setResult("is ok");
		ctx.channel().writeAndFlush(JSONObject.toJSONString(resp));
		ctx.channel().writeAndFlush("\r\n");*/
		
		Media media = Media.newInstance();
		Response result = media.process(request);
		
		ctx.channel().writeAndFlush(JSONObject.toJSONString(result));
		ctx.channel().writeAndFlush("\r\n");
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.close();
	}

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		if(evt instanceof IdleStateEvent) {
			IdleStateEvent event = (IdleStateEvent)evt;
			if(event.state().equals(IdleState.READER_IDLE)) {
				System.out.println("READER_IDLE 读超时");
				ctx.close();
			} else if(event.state().equals(IdleState.WRITER_IDLE)) {
				System.out.println("WRITER_IDLE 写超时");
			} else if(event.state().equals(IdleState.ALL_IDLE)) {
				System.out.println("ALL_IDLE 读写超时");
				ctx.channel().writeAndFlush("ping\r\n");
			}
		}
	}

	
}
